package com.flycms.modules.group.controller.front;

import cn.hutool.dfa.WordTree;
import com.flycms.common.constant.UserConstants;
import com.flycms.common.utils.*;
import com.flycms.common.utils.page.Pager;
import com.flycms.common.validator.Order;
import com.flycms.common.validator.Sort;
import com.flycms.framework.web.controller.BaseController;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.framework.web.page.TableDataInfo;
import com.flycms.modules.data.domain.Label;
import com.flycms.modules.data.domain.LabelMerge;
import com.flycms.modules.data.service.ILabelMergeService;
import com.flycms.modules.data.service.ILabelService;
import com.flycms.modules.elastic.service.IElasticSearchService;
import com.flycms.modules.group.domain.*;
import com.flycms.modules.group.domain.dto.GroupTopicCommentDTO;
import com.flycms.modules.group.domain.dto.GroupTopicDTO;
import com.flycms.modules.group.domain.vo.GroupTopicVO;
import com.flycms.modules.group.service.*;
import com.flycms.modules.score.service.IScoreRuleService;
import com.flycms.modules.site.domain.Site;
import com.flycms.modules.site.service.ISiteService;
import com.flycms.modules.user.domain.User;
import com.flycms.modules.user.service.IUserAccountService;
import com.flycms.modules.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小组话题Controller
 * 
 * @author admin
 * @date 2020-07-08
 */
@Controller
public class GroupTopicController extends BaseController
{
    @Autowired
    private IGroupTopicService groupTopicService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IGroupUserService groupUserService;

    @Autowired
    private IGroupTopicCommentService groupTopicCommentService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private IScoreRuleService scoreRuleService;

    @Autowired
    private IElasticSearchService elasticSearchService;

    @Autowired
    private IGroupTopicFollowService groupTopicFollowService;

    @Autowired
    private ILabelService labelService;

    @Autowired
    private ILabelMergeService labelMergeService;

    /////////////////////////////////
    ///////       增加       ////////
    /////////////////////////////////

    /**
     * 添加话题
     *
     * @return
     */
    @GetMapping("/user/group/{groupId}/topic/create")
    public String create(@PathVariable("groupId") String groupId,ModelMap modelMap){
        if (!StrUtils.checkLong(groupId)) {
            return forward("/error/404");
        }
        Group group= groupService.findGroupById(Long.valueOf(groupId));
        if(group == null){
            return forward("/error/404");
        }
        User user = SessionUtils.getUser();
        if(user == null){
            modelMap.addAttribute("message","用户未登录");
            return theme.getPcTemplate("/error/error_tip");
        }
        GroupUser findgroupUser = new GroupUser();
        findgroupUser.setGroupId(group.getId());
        findgroupUser.setUserId(user.getId());
        GroupUser userDTO=groupUserService.findGroupUser(findgroupUser);
        if(userDTO == null || userDTO.getStatus() == 0){
            modelMap.addAttribute("message","用户未加入或者加入申请未审核");
            return theme.getPcTemplate("/error/error_tip");
        }
        modelMap.addAttribute("group",group);
        modelMap.addAttribute("groupId",groupId);
        return theme.getPcTemplate("topic/create");
    }

    /**
     * 新增群组(小组)话题
     */
    @PostMapping("/user/topic/create")
    @ResponseBody
    public AjaxResult add(GroupTopicVO topicVo) throws Exception
    {
        if(StrUtils.isEmpty(topicVo.getGroupId())){
            return AjaxResult.error("小组ID不得为空！");
        }
        if (!StrUtils.checkLong(topicVo.getGroupId())) {
            return AjaxResult.error("未选择加入发布的小组");
        }
        if(StrUtils.isEmpty(topicVo.getTitle())){
            return AjaxResult.error("标题不得为空！");
        }
        if(StrUtils.isEmpty(topicVo.getContent())){
            return AjaxResult.error("内容不得为空！");
        }

        if (UserConstants.NOT_UNIQUE.equals(groupTopicService.checkGroupTopicNameUnique(topicVo)))
        {
            return AjaxResult.error("发布标题'" + topicVo.getTitle() + "'失败，请勿重复发布！");
        }
        return groupTopicService.insertGroupTopic(topicVo);
    }

    /**
     * 新增群组(小组)话题评论
     */
    @PostMapping("/user/add/topic/comment")
    @ResponseBody
    public AjaxResult addComment(@RequestParam(value = "topicId", required = false) String topicId,
                          @RequestParam(value = "content", required = false) String content,
                          @RequestParam(value = "ispublic", required = false) String ispublic){
        if(StrUtils.isEmpty(topicId)){
            return AjaxResult.error("话题id不得为空！");
        }
        if (!StrUtils.checkLong(topicId)) {
            return AjaxResult.error("话题id错误");
        }

        if(StrUtils.isEmpty(content)){
            return AjaxResult.error("内容不得为空！");
        }

        GroupTopicDTO topic= groupTopicService.findGroupTopicById(Long.valueOf(topicId));
        if(topic == null){
            return AjaxResult.error("话题不存在");
        }
        if("1".equals(topic.getIscomment())){
            return AjaxResult.error("该话题不允许评论");
        }
        GroupTopicComment topicComment = new GroupTopicComment();
        topicComment.setTopicId(Long.valueOf(topicId));
        topicComment.setContent(content);
        topicComment.setIspublic(Integer.valueOf(ispublic));
        topicComment.setUserId(SessionUtils.getUser().getId());
        if (UserConstants.NOT_UNIQUE.equals(groupTopicCommentService.checkGroupTopicCommentUnique(topicComment)))
        {
            return AjaxResult.error("该评论您已发布！");
        }
        Site site=siteService.selectSite(478279584488632368l);
        if(site != null){
            //是否发帖审核  0不允许，1允许
            if(site.getCommentVerify() ==1){
                topicComment.setStatus(0);
            }else{
                topicComment.setStatus(1);
            }
        }
        int conut=groupTopicCommentService.insertGroupTopicComment(topicComment);
        if(conut > 0){
            if(topicComment.getStatus() == 1){
                AjaxResult.success("评论已提交，需要审核后才能显示！",topicComment.getTopicId().toString());
            }
            groupTopicService.updateCountComment(Long.valueOf(topicId));
            return AjaxResult.success("发布成功",topicComment.getTopicId().toString());
        }
        return AjaxResult.error("未知错误！");
    }

    /**
     * 新增回复评论
     */
    @PostMapping("/user/add/topic/reply")
    @ResponseBody
    public AjaxResult addReply(@RequestParam(value = "commentId", required = false) String commentId,
                          @RequestParam(value = "content", required = false) String content){
        if(StrUtils.isEmpty(commentId)){
            return AjaxResult.error("回复内容id不得为空！");
        }
        if (!StrUtils.checkLong(commentId)) {
            return AjaxResult.error("内容id错误");
        }
        if(StrUtils.isEmpty(content)){
            return AjaxResult.error("内容不得为空！");
        }
        GroupTopicCommentDTO comment=groupTopicCommentService.findGroupTopicCommentById(Long.valueOf(commentId));
        if(comment == null){
            return AjaxResult.error("回复的内容不存在");
        }
        GroupTopicComment topicComment = new GroupTopicComment();
        topicComment.setTopicId(comment.getTopicId());
        topicComment.setReferId(Long.valueOf(commentId));
        topicComment.setContent(content);
        topicComment.setUserId(SessionUtils.getUser().getId());
        if (UserConstants.NOT_UNIQUE.equals(groupTopicCommentService.checkGroupTopicCommentUnique(topicComment)))
        {
            return AjaxResult.error("该评论您已发布！");
        }
        Site site=siteService.selectSite(478279584488632368l);
        if(site != null){
            //是否发帖审核  0不允许，1允许
            if(site.getCommentVerify() ==1){
                topicComment.setStatus(0);
            }else{
                topicComment.setStatus(1);
            }
        }
        int conut=groupTopicCommentService.insertGroupTopicComment(topicComment);
        if(conut > 0){
            if(topicComment.getStatus() == 1){
                AjaxResult.success("评论已提交，需要审核后才能显示！",topicComment.getTopicId().toString());
            }
            groupTopicService.updateCountComment(comment.getTopicId());
            return AjaxResult.success("发布成功",topicComment.getTopicId().toString());
        }
        return AjaxResult.error("未知错误！");
    }

    /**
     * 用户关注话题操作
     */
    @PostMapping("/topic/user/follow")
    @ResponseBody
    public AjaxResult add(@RequestParam("id") String id)
    {
        if(StrUtils.isEmpty(id)){
            return AjaxResult.error("话题id不得为空");
        }
        if (!StrUtils.checkLong(id)) {
            return AjaxResult.error("话题id错误");
        }
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error(101,"请登录后关注");
        }
        GroupTopicFollow groupTopicFollow=new GroupTopicFollow();
        groupTopicFollow.setUserId(user.getId());
        groupTopicFollow.setTopicId(Long.valueOf(id));
        if (!UserConstants.NOT_UNIQUE.equals(groupTopicFollowService.checkTopicFollowUnique(groupTopicFollow.getTopicId(),groupTopicFollow.getUserId()))) {
            groupTopicFollowService.insertGroupTopicFollow(groupTopicFollow);
            groupTopicService.updateTopicFollowCount(groupTopicFollow.getTopicId());
            return AjaxResult.success("已关注话题");
        }else{
            groupTopicFollowService.deleteTopicUserFollow(groupTopicFollow.getTopicId(),groupTopicFollow.getUserId());
            groupTopicService.updateTopicFollowCount(groupTopicFollow.getTopicId());
            return AjaxResult.error("取消关注");
        }
    }
    /////////////////////////////////
    ///////        刪除      ////////
    /////////////////////////////////
    /**
     * 删除用户账户
     */
    @PostMapping("/user/topic/delete")
    @ResponseBody
    public AjaxResult remove(@RequestParam("id") String id)
    {
        if (!StrUtils.checkLong(id)) {
            return AjaxResult.error("话题id错误");
        }
        GroupTopicDTO topic= groupTopicService.findGroupTopicById(Long.valueOf(id));
        if(topic == null){
            return AjaxResult.error("话题不存在");
        }
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error("未登录或者用户不存在");
        }
        if(!user.getId().equals(topic.getUserId())){
            return AjaxResult.error("不能删除不属于您的文章！");
        }
        int count = groupTopicService.updateDeleteGroupTopicById(Long.valueOf(id));
        if(count == 0){
            return AjaxResult.error("删除话题失败！");
        }
        groupService.updateCountTopic(topic.getGroupId());
        groupTopicService.updateUserCountTopic(topic.getUserId());
        groupTopicService.updateCountComment(topic.getId());
        // 删帖扣分
        scoreRuleService.scoreRuleBonus(topic.getId(), 547413101788803091L,topic.getId());
        elasticSearchService.deleteDocument("topic",id);
        return AjaxResult.success("话题删除成功","/group/"+topic.getGroupId());
    }

    /////////////////////////////////
    ///////        修改      ////////
    /////////////////////////////////
    /**
     * 添加话题
     *
     * @return
     */
    @GetMapping("/user/topic/update/{topicId}")
    public String updateGroupTopic(@PathVariable("topicId") String topicId,ModelMap modelMap){
        if (!StrUtils.checkLong(topicId)) {
            return forward("/error/404");
        }
        User user = SessionUtils.getUser();
        if(user == null){
            modelMap.addAttribute("message","用户未登录");
            return theme.getPcTemplate("/error/error_tip");
        }

        GroupTopicDTO content= groupTopicService.findGroupTopicById(Long.valueOf(topicId));
        if(content == null){
            return forward("/error/404");
        }
        if(!user.getId().equals(content.getUserId())){
            modelMap.addAttribute("message","不能修改不属于您的文章！");
            return theme.getPcTemplate("/error/error_tip");
        }
        List<String> labelList = labelMergeService.queryLabelListById(Long.valueOf(content.getId()));
        content.setLabels(StringUtils.join(labelList.toArray(),","));
        modelMap.addAttribute("content",content);
        return theme.getPcTemplate("topic/create");
    }


    /**
     * 修改小组话题
     */
    /**
     * 新增群组(小组)
     */
    @PostMapping("/user/topic/update")
    @ResponseBody
    public AjaxResult updateGroupTopic(GroupTopicVO topicVo) throws Exception
    {
        if (!StrUtils.checkLong(topicVo.getId())) {
            return AjaxResult.error("话题id错误");
        }
        GroupTopicDTO topic= groupTopicService.findGroupTopicById(Long.valueOf(topicVo.getId()));
        if(topic == null){
            return AjaxResult.error("话题不存在");
        }
        User user = SessionUtils.getUser();
        if(user == null){
            return AjaxResult.error("未登录或者用户不存在");
        }
        if(!user.getId().equals(topic.getUserId())){
            return AjaxResult.error("不能修改不属于您的文章！");
        }
        topicVo.setUserId(topic.getUserId().toString());
        topicVo.setGroupId(topic.getGroupId().toString());
        if (UserConstants.NOT_UNIQUE.equals(groupTopicService.checkGroupTopicNameUnique(topicVo)))
        {
            return AjaxResult.error("修改标题'" + topicVo.getTitle() + "'失败，请勿重复发布！");
        }
        topicVo.setColumnId(topic.getColumnId().toString());
        topicVo.setCreateTime(topic.getCreateTime());
        return groupTopicService.updateGroupTopic(topicVo);
    }

    /**
     * 更新话题浏览数量
     */
    @GetMapping("/topic/update/view")
    @ResponseBody
    public AjaxResult updateCountView(@RequestParam("id") String id)
    {
        if (StrUtils.checkLong(id)) {
            groupTopicService.updateCountView(Long.valueOf(id));
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    /////////////////////////////////
    ///////        查詢      ////////
    /////////////////////////////////
    /**
     * 发现首页
     *
     * @return
     */
    @GetMapping(value = {"/topic/" , "/topic/index", "/topic/index-p-{p}"})
    public String topicList(@PathVariable(value = "p", required = false) String p,ModelMap modelMap){
        if(p == null) p = "1";
        modelMap.addAttribute("p", p);
        return theme.getPcTemplate("topic/list_topic");
    }

    /**
     * 热门内容首页
     *
     * @return
     */
    @GetMapping(value = {"/topic-hot/" , "/topic-hot/index","/topic-hot-p-{p}"})
    public String topicHotList(@PathVariable(value = "p", required = false) String p,ModelMap modelMap){
        if(p == null) p = "1";
        modelMap.addAttribute("p", p);
        return theme.getPcTemplate("topic/list_hot");
    }

    /**
     * 推荐内容首页
     *
     * @return
     */
    @GetMapping(value = {"/recommend/" , "/recommend/index","/recommend/index-p-{p}"})
    public String topicRecommendList(@PathVariable(value = "p", required = false) String p,ModelMap modelMap){
        if(p == null) p = "1";
        modelMap.addAttribute("p", p);
        return theme.getPcTemplate("topic/list_recommend");
    }

    /**
     * 详细内容
     *
     * @return
     */
    @GetMapping(value = {"/topic/{id}","/topic/{id}-p-{p}"})
    public String detail(@PathVariable("id") String id,@PathVariable(value = "p", required = false) String p, ModelMap modelMap){
        if (!StrUtils.checkLong(id)) {
            return forward("/error/404");
        }
        GroupTopicDTO content=groupTopicService.findGroupTopicById(Long.valueOf(id));
        if(content == null){
            return forward("/error/404");
        }
        if(!"1".equals(content.getIsaudit())){
            modelMap.addAttribute("message","该内容小组管理员未审核");
            return theme.getPcTemplate("/error/error_tip");
        }
        if(!"1".equals(content.getStatus())){
            modelMap.addAttribute("message","该内容管理员未审核或者未审核通过，请联系管理员");
            return theme.getPcTemplate("/error/error_tip");
        }
        if(p == null) p = "1";
        //标题分割成SEO关键词
        List<String> keywords=IKAnalyzerUtils.cut(content.getTitle(),false);
        content.setKeywords(StringUtils.join(keywords, ","));

        modelMap.addAttribute("p", p);
        modelMap.addAttribute("content",content);
        return theme.getPcTemplate("topic/detail");
    }

    /**
     * 查询小组话题列表
     */
    @GetMapping("/user/group-topic-list-{id}")
    @ResponseBody
    public TableDataInfo list(@PathVariable("id") String id,
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @Sort @RequestParam(defaultValue = "create_time") String sort,
                              @Order @RequestParam(defaultValue = "desc") String order)
    {
        GroupTopic groupTopic = new GroupTopic();
        groupTopic.setGroupId(Long.valueOf(id));
        Pager<GroupTopicDTO> pager = groupTopicService.selectGroupTopicPager(groupTopic, pageNum, pageSize, sort, order);
        return getDataTable(pager.getList(),pager.getTotal());
    }
}
